<?php

namespace App\Http\Servers\Admin;

use App\ChunkInfoFieldLines;
use App\InfoSortLines;
use App\Sort;

class ChunkServer
{
    private $sort;
    private $infoSortline;
    private $chunkInfoFieldLines;

    public function __construct(Sort $sort, InfoSortLines $infoSortLines, ChunkInfoFieldLines $chunkInfoFieldLines)
    {
        $this->sort = $sort;
        $this->infoSortline = $infoSortLines;
        $this->chunkInfoFieldLines = $chunkInfoFieldLines;
    }

    //得到信息模块的模版
    public function getChunkTheme()
    {
        $tmpChunkThemes = glob(config('app.chunk_theme'));
        foreach ($tmpChunkThemes as $theme) {
            $chunkThemes[] = explode('.', basename($theme))[0];
        }

        return $chunkThemes;
    }

    //需要超级管理员权限
    public function needRoot()
    {
        return false;
        if (!(bool)\Auth::guard('admin')->user()->is_root) {
            return message(false, '添加失败', '只有超级管理员才能进行此操作!');
        } else {
            return false;
        }
    }

    //需要模块下没有分类
    public function noSort($chunkId)
    {
        $num = $this->sort
            ->where('chunk', $chunkId)
            ->count();
        if ($num > 0) {
            return message(false, '删除失败', '该模块下存在分类,无法删除!');
        } else {
            return false;
        }
    }

    //需要模块下没有产品
    public function noInfo($chunkId)
    {
        $num = $this->infoSortline
            ->where('chunk', $chunkId)
            ->count();
        if ($num > 0) {
            return message(false, '删除失败', '该模块下存在信息,无法删除!');
        } else {
            return false;
        }
    }

    //安全删除验证
    public function sofeVerify($chunkId)
    {
        if ($message = $this->needRoot($chunkId)) {
            return $message;
        }

        if ($message = $this->noSort($chunkId)) {
            return $message;
        }

        if ($message = $this->noInfo($chunkId)) {
            return $message;
        }

        return false;
    }

    //重新设置拓展信息
    public function setInfoFields($chunk, $infoFields)
    {
        $this->chunkInfoFieldLines->where('chunk', $chunk)->delete();
        $infoFields = explode(',', rtrim($infoFields, ','));
        foreach ($infoFields as $infofield) {
            $this->chunkInfoFieldLines->create(['chunk' => $chunk, 'info_field' => $infofield]);
        }
    }
}